package com.szhn.userservice.controller;


import com.szhn.common.responsejson.R;
import com.szhn.common.utils.JwtUtils;
import com.szhn.userservice.entity.User;
import com.szhn.userservice.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2022-10-28
 */
@RestController
@RequestMapping("/userservice/user")
@CrossOrigin
public class UserController {

    @Autowired
    private UserService userService;

    @ApiOperation("登录功能")
    @PostMapping("login")
    public R loginUser(@RequestBody User user){
        //返回token值，使用jwt生成
        String token = userService.login(user);
        return token != null ? R.ok().data("token",token) : R.error();
    }


    @ApiOperation("注册功能")
    @PostMapping("register")
    public R registerUser(@RequestBody User user){
        boolean flag = userService.register(user);
        return flag ? R.ok() : R.error();
    }

    @ApiOperation("根据token字符串获取用户id")
    @GetMapping("getMenberInfo")
    public R getMemberInfo(HttpServletRequest request){
        //调用jwt工具类的方法。根据request对象获取头信息，返回用户id
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        //查询数据库根据用户id获取用户信息
        User member = userService.getById(memberId);
        return member != null ? R.ok().data("userInfo",member) : R.error();
    }

}

